home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / VideoToolbox 96.06.15 / (Demos) / Sandstorm.c < prev    next >
C/C++ Source or Header  |  1996-03-05  |  12KB  |  329 lines

  1. /*
  2. Sandstorm.c
  3. Copyright © 1989-1995 Denis Pelli
  4. This program shows a noise movie, a dynamic random checkerboard at whatever your
  5. display's frame rate is, e.g. 67 Hz!
  6. The key routine, which shows each frame, is the VideoToolbox routine CopyBitsQuickly().
  7.  
  8. To get a true impression of white noise you need to compute lots of noise
  9. frames, so give it as much memory as you can, e.g. 3 MB. (Use the Finder Get
  10. Info command.) Sandstorm fills all the memory you give it with pre-computed
  11. noise, which does take some time. Each displayed frame is taken from a random
  12. offset within that noise.
  13.  
  14. Note: the amount of data that has to be transfered by CopyBitsQuickly() in each
  15. frame is proportional to window area and the bits/pixel of the display, as set by
  16. Control Panel Monitors. 
  17.  
  18. Sandstorm--not CopyBitsQuickly--calls WaitNextEvent() before each
  19. frame, in order to be responsive to the mouse, and this results in occasional
  20. pauses as the Mac takes time out to do various chores.
  21.  
  22. NOTE:
  23. This program is written to work on every Mac in existence under the widest possible
  24. range of Mac OS versions. Thus it doesn't use GWorlds, which requires System 7, though
  25. they would make the code shorter and easier to read. So DON'T read this program
  26. as a model for your code. Most programs should Require(gestalt32BitQD); and use GWorlds and
  27. CopyWindows. They'll make your life much easier. E.g. see the demo NoiseVBL.c.
  28.  
  29. NOT MULTIFINDER FRIENDLY:
  30. Walt Makous writes, "I ran Sandstorm by clicking on the icon for the application, 
  31. interrupted it by clicking outside the window, and then resumed it by clicking 
  32. on the window again.  This locks the keyboard so that the only way I can get back 
  33. control is by using the programmer's switch." REPLY: Alas, I've never had any need 
  34. to write polite applications that gracefully share the computer with other applications. 
  35. Experiments always seem to deserve hogging it all. The Sandstorm demo allows you to 
  36. invoke other applications, because it doesn't obscure the whole window, but it doesn't 
  37. act like a good citizen in paying attention to the messages it gets from the Finder 
  38. about what happened. (I would go ahead and make the demos multifinder-friendly if I 
  39. knew how, but it hasn't seemed worth learning just for the sake of the demos.) 
  40.  
  41. HISTORY:
  42. 11/23/88 dgp derived from truenoiseDemo2.c
  43. 4/7/89 dgp     I removed nearly all the hardware dependencies. The only remaining one
  44.             is the call to NewFieldTFB(). I don't know how to get rid of that, short
  45.             of writing a VBL task.
  46. 9/29/89 dgp I've nearly updated this to THINK C 4.0, but the call to TickCount, 
  47.             refers to the old profiler, and I don't have time to figure this out now.
  48. 10/28/89 dgp I replaced the call to NewFieldTFB() by a call to GDSetEntries() which
  49.             is a device-independent way to wait for the end of frame.
  50. 7/19/90 dgp Unfortunately the built-in video on the Mac IIci is buggy and doesn't
  51.             support the cscSetEntries call.
  52. 10/17/90 dgp Yay. Finally removed last bugs! Replaced SlotToScreenDevice() by
  53.             AddressToScreenDevice() in order to make it compatible with built-in video
  54.             on Mac IIci, IIsi, and LC. Removed the cscSetEntries call for compatibility
  55.             with Mac IIci built-in video.(Apple has acknowledged bug, but bug is
  56.             still present in System 6.07.) Fixed bug whereby resizing window on other
  57.             than the main screen left window blank until it was dragged again. 
  58.             Removed unused variables. Added zoom box.
  59. 10/18/90 dgp Tidied up. Now zooms onto screen with largest intersection, and zooms back
  60.             to original size. Uses as much memory as user allocates to program. 
  61.             Window now always confines itself to a single screen, but can be dragged
  62.             anywhere.
  63. 10/20/90 dgp Copied code from VideoTest to close window and quit on Command-W or
  64.             Command-. Prevented window title bar from being hidden behind the menu
  65.             bar.
  66. 7/22/91    dgp    Made compatible with MPW C. This required changing INT_MAX to SHRT_MAX.
  67.             However, performance is slow, since CopyBitsQuickly.c doesn't generate
  68.             hand-tuned assembly code when using MPW C.
  69. 8/6/91    dgp    Replaced randU() by RandFill(), which runs twice as fast.
  70. 8/24/91    dgp    Made compatible with THINK C 5.0.
  71. 7/20/92    dgp    tidied up the comments slightly. Confirmed compatibility with 32-bit
  72.             addressing.
  73. 8/27/92    dgp    replace SysEnvirons() by Gestalt()
  74. 1/13/93 dgp    changed defaults to maximize speed.
  75. 9/3/93    dgp    added call to ShieldCursor() for compatibility with nonstandard
  76.             video devices, e.g. Radius PowerView.
  77. 6/3/94    dgp    replaced low-memory global MBarHeight by GetMBarHeight().
  78. 9/5/94 dgp removed assumption in printf's that int==short.
  79. */
  80. #include "VideoToolbox.h"
  81. #if UNIVERSAL_HEADERS
  82.     #include <LowMem.h>
  83. #else
  84.     #define LMGetMBarHeight() (* (short *) 0x0BAA)
  85.     #define LMSetMBarHeight(MBarHeightValue) ((* (short *) 0x0BAA) = (MBarHeightValue))
  86. #endif
  87. void main(void);
  88. Boolean ZoomedOut(WindowPtr w);
  89. #define RAISE_PRIORITY    0    /* Optional. Contrary to Apple's rules,    */
  90.                             /* but speeds up the display. */
  91. #define SCROLL_BAR 15        /* Standard width of scroll bar */
  92. #define WAIT_NEXT_EVENT 0
  93.  
  94. void Sandstorm(void);
  95.  
  96. void main(void)
  97. {
  98.     StackGrow(4000);
  99.     Require(gestalt8BitQD);
  100.     Sandstorm();
  101. }
  102. void Sandstorm()
  103. {
  104.     register short *bufferPtr;
  105.     int i;
  106.     char string[40];
  107.     PixMap sand;
  108.     Rect r,unzoomedRect,gdRect;
  109.     GDHandle device;
  110.     WindowPtr window,aWindow,oldPort;
  111.     PixMap **myPixMapHandle;
  112.     BitMap buffer;
  113.     long bufferBytes;
  114.     size_t sandBytes;
  115.     Boolean done=0,update;
  116.     long reSize;
  117.     int windowEvent=inDesk;
  118.     Boolean zoomedOut;
  119.     WStateData *wStateData;
  120.     RgnHandle ignoreRgn;
  121.     int pixelSize;
  122.     Point pt;
  123.     EventRecord event;
  124.     
  125.     assert(StackSpace()>4000);
  126.     
  127.     /* INITIALIZE QuickDraw */
  128.     MaxApplZone();                        /* Expand heap to the limit. */
  129.     InitGraf(&qd.thePort);
  130.     InitFonts();
  131.     InitWindows();
  132.     InitCursor();
  133.     GetPort(&oldPort);
  134.     device=GetMainDevice();
  135.  
  136.     /* open a window on the device */
  137.     ignoreRgn=NewRgn();
  138.     SetRect(&r,0,0,192+SCROLL_BAR,192+SCROLL_BAR);
  139.     CenterRectInRect(&r,&(*device)->gdRect);
  140.     window=NewCWindow(NULL
  141.         ,&r,"\pNow computing noise ...",TRUE,zoomDocProc,(WindowPtr) -1L,TRUE,0L);
  142.     myPixMapHandle = ((CGrafPtr)window)->portPixMap;
  143.     MoveHHi((Handle) myPixMapHandle);
  144.     HLock((Handle) myPixMapHandle);
  145.  
  146.     /* Compute noise */
  147.     /* allocate buffer BitMap */
  148.     buffer.rowBytes=1024;
  149.     MaxApplZone();
  150.     bufferBytes = FreeMem();
  151.     bufferBytes-=100000L;    /* Grab most of available space. */
  152.     bufferBytes -= bufferBytes%buffer.rowBytes;
  153.     buffer.baseAddr=NULL;
  154.     for(;bufferBytes>0;bufferBytes -= buffer.rowBytes){
  155.         buffer.baseAddr = NewPtr(bufferBytes);
  156.         if (buffer.baseAddr!=NULL)break;
  157.     }
  158.     if(buffer.baseAddr==NULL)PrintfExit("\007Sorry, not enough memory for buffers.\n");
  159.     SetRect(&buffer.bounds,0,0,buffer.rowBytes*8L,bufferBytes/buffer.rowBytes);
  160.  
  161.     /* Fill buffer with noise. */
  162.     bufferPtr = (short *) buffer.baseAddr;
  163.     RandFill(buffer.baseAddr,bufferBytes);
  164.  
  165.     /* Show noise */
  166.     SetPort(window);
  167.     reSize=0;
  168.     while (1) {
  169.         wStateData=(*((WStateData **)((WindowPeek)window)->dataHandle));
  170.         unzoomedRect=wStateData->userState;
  171.         zoomedOut=ZoomedOut(window);
  172.         if(reSize){
  173.             SizeWindow(window,LoWord(reSize),HiWord(reSize),TRUE);
  174.             reSize=0L;
  175.         }
  176.         device=GetWindowDevice(window);
  177.         if(device==NULL){
  178.             done=1;
  179.             break;
  180.         }
  181.         r=window->portRect;
  182.         LocalToGlobalRect(&r);
  183.         gdRect=(*device)->gdRect;
  184.         /* leave room for window's title bar */
  185.         gdRect.top+=r.top-1-(*((WindowPeek)window)->strucRgn)->rgnBBox.top;
  186.         /* leave room for menu bar */
  187.         if(device==GetMainDevice())gdRect.top+=LMGetMBarHeight();
  188.         SectRect(&gdRect,&r,&r);
  189.         pixelSize=(**(**device).gdPMap).pixelSize;
  190.         i=r.left-(*device)->gdRect.left;
  191.         i=(i*pixelSize+16 & ~31)/pixelSize-i;    /* move to nearest 32-bit boundary */
  192.         OffsetRect(&r,i,0);                        /* Assumes window is >16 bits wide */
  193.         SectRect(&gdRect,&r,&r);
  194.         MoveWindow(window,r.left,r.top,TRUE);
  195.         OffsetRect(&r,-r.left,-r.top);
  196.         sand = **(*device)->gdPMap;    /* Initialize PixMap fields from screen */
  197.         sand.bounds=r;
  198.         sand.bounds.right  -=SCROLL_BAR;    /* Leave room for the scroll bars */
  199.         sand.bounds.bottom -=SCROLL_BAR;
  200.         sand.bounds.right=(sand.bounds.right*sand.pixelSize+14 & ~31)/sand.pixelSize;
  201.             /* round to multiple of 32 bits */
  202.         if(sand.bounds.right<32)sand.bounds.right=32;
  203.         sand.rowBytes = (sand.bounds.right*sand.pixelSize + 31 & ~31)/8;
  204.             /* round up to multiple of 32 bits (redundant) */
  205.         sandBytes = (size_t) sand.rowBytes * (size_t) sand.bounds.bottom;
  206.         if(bufferBytes/2 < sandBytes)
  207.         {
  208.             /* restrict height by amount of noise available */
  209.             sand.bounds.bottom=bufferBytes/sand.rowBytes/2;
  210.             sandBytes = (size_t) sand.rowBytes * (size_t) sand.bounds.bottom;
  211.         }    
  212.         sand.rowBytes |= 0x8000;    /* Mark it as a PixMap */
  213.         sand.pmVersion=0;
  214.         sand.packType=0;
  215.         sand.packSize=0;
  216.         sand.planeBytes=0;
  217.         sand.pmReserved=0;
  218.         SizeWindow(window
  219.             ,sand.bounds.right+SCROLL_BAR,sand.bounds.bottom+SCROLL_BAR,TRUE);
  220.         EraseRect(&window->portRect);
  221.         DrawGrowIcon(window);
  222.         if(zoomedOut && windowEvent!=inGrow && windowEvent!=inDrag){
  223.             wStateData=(*((WStateData **)((WindowPeek)window)->dataHandle));
  224.             r=window->portRect;
  225.             LocalToGlobalRect(&r);
  226.             r.left-=1;
  227.             r.right-=2;
  228.             wStateData->stdState=r;        
  229.             wStateData->userState=unzoomedRect;
  230.         }
  231.         sprintf(string,"%dx%dx%d bits"
  232.             ,(int)sand.bounds.right,(int)sand.bounds.bottom,(int)sand.pixelSize);
  233.         SetWTitle(window,c2pstr(string));
  234.         FlushEvents(everyEvent,0);
  235.         DiffRgn(GetGrayRgn(),((WindowPeek)window)->strucRgn,ignoreRgn);
  236.         while (1) {
  237.             update=0;            /* don't update window frame unless necessary */
  238.             #if RAISE_PRIORITY
  239.                 SetPriority(2);    /* Get more speed by suppressing keyboard, mouse, and ticks. */
  240.             #endif
  241.             sand.baseAddr = buffer.baseAddr;
  242.             /* choose grain that won't overflow short argument to nrand() */
  243.             i=(bufferBytes/SHRT_MAX+3)&~3;    /* round up to multiple of 4 */
  244.             sand.baseAddr += nrand((bufferBytes-sandBytes)/i)*(long)i;
  245.             if(((WindowPeek)window)->hilited){
  246.                 // ShieldCursor tells nonstandard video devices which pixels may change.
  247.                 pt.h=pt.v=0;
  248.                 LocalToGlobal(&pt);
  249.                 ShieldCursor(&sand.bounds,pt);
  250.                 CopyBitsQuickly((BitMap *)&sand,(BitMap *)*myPixMapHandle
  251.                     ,&sand.bounds,&sand.bounds,srcCopy,NULL);
  252.                 ShowCursor();
  253.             }
  254.             #if RAISE_PRIORITY
  255.                 SetPriority(0);    /* Revive keyboard and mouse. */
  256.             #endif
  257.             #if WAIT_NEXT_EVENT
  258.                if(WaitNextEvent(mDownMask+keyDownMask,&event,0,ignoreRgn)){
  259.                #else
  260.                if(GetNextEvent(mDownMask+keyDownMask,&event)){
  261.                #endif
  262.                 switch(event.what){
  263.                 case keyDown:
  264.                     if(event.modifiers & cmdKey) switch(event.message & charCodeMask) {
  265.                         case '.':
  266.                         case 'w':
  267.                         done=1;
  268.                     }
  269.                     break;
  270.                 case mouseDown:
  271.                     update=1;
  272.                     windowEvent=FindWindow(event.where,&aWindow);
  273.                     if(aWindow==window){
  274.                         switch(windowEvent){
  275.                         case inDrag:
  276.                             DragWindow(window,event.where,&qd.screenBits.bounds);
  277.                             break;
  278.                         case inGoAway:
  279.                             done=TrackGoAway(window,event.where);
  280.                             break;
  281.                         case inGrow:
  282.                             r.top=r.left=32+SCROLL_BAR;    /* minimum size */
  283.                             r.bottom=r.right=1024+SCROLL_BAR;    /* max size */
  284.                             reSize = GrowWindow(window,event.where,&r);
  285.                             break;
  286.                         case inZoomIn:
  287.                         case inZoomOut:
  288.                             Zoom(window,windowEvent,&event);
  289.                             break;
  290.                         case inContent:
  291.                             break;
  292.                         default:
  293.                             update=0;
  294.                             break;
  295.                         }
  296.                         break;
  297.                     }
  298.                     break;
  299.                 }
  300.             }            
  301.             if(update || done)break;
  302.         }
  303.         if(done)break;
  304.     }
  305.     SetPort(oldPort);
  306.     DisposeRgn(ignoreRgn);
  307.     DisposPtr(buffer.baseAddr);
  308.     DisposeWindow(window);
  309. }
  310.  
  311. Boolean ZoomedOut(WindowPtr w)
  312. /* Determine whether window is "standard" size, i.e. zoomed out. */
  313. {
  314.     Point pt;
  315.     Rect r,myRect;
  316.     Boolean zoomedOut;
  317.     
  318.     myRect=(*((WStateData **)((WindowPeek)w)->dataHandle))->stdState;
  319.     pt.h=0;
  320.     pt.v=0;
  321.     LocalToGlobal(&pt);
  322.     r=w->portRect;
  323.     OffsetRect(&r,pt.h,pt.v);
  324.     zoomedOut= r.top==myRect.top
  325.         && r.left==myRect.left
  326.         && r.bottom==myRect.bottom
  327.         && r.right==myRect.right;
  328.     return zoomedOut;
  329. }